const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    backgroundColor: '#000000',
    scene: {
        create: create,
        update: update
    },
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 0 },
            debug: false
        }
    },
    render: {
        transparent: false
    },
    scene: {
        preload: preload,
        create: create,
        update: update
    },
    parent: 'game-container'
};

const game = new Phaser.Game(config);
let player;
let food;
let score = 0;
let scoreText;

function preload() {    // 不再需要预加载图片资源
    this.load.on('complete', () => {// 预加载资源
        this.load.image('player', 'assets/player.png');
        this.load.image('food', 'assets/food.png');
        console.log('资源加载完成');
    });
}

// 生成随机颜色
function getRandomColor() {
    const colors = [0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff, 0x00ffff];
    return colors[Math.floor(Math.random() * colors.length)];

}

function create() {
    // 创建重新开始按钮(初始隐藏)
    const restartButton = this.add.text(400, 300, '重新开始', { 
        fontSize: '32px', 
        fill: '#ffffff',
        backgroundColor: '#4a4a4a',
        padding: { x: 20, y: 10 }
    })
    .setOrigin(0.5)
    .setInteractive()
    .setVisible(false);
    
    // 按钮点击事件
    restartButton.on('pointerdown', () => {
        this.scene.restart();
    });

    // 创建玩家球体(亮红色圆形带白边)
    // 先创建图形对象
    player = this.add.circle(400, 300, 15, 0xff5555); // 更亮的红色，无边框
    
    // 然后启用物理系统
    this.physics.add.existing(player);
    this.physics.world.enable(player);
    
    // 最后设置物理属性
    player.body.setCollideWorldBounds(true);
    player.body.setBounce(0.2);
    player.body.setDrag(100);
    player.mass = 15; // 玩家初始质量(半径)
    player.score = 0;

    // 创建食物组
    food = this.physics.add.group();

    // 创建敌人组
    enemies = this.physics.add.group();
    for (let i = 0; i < 5; i++) {
        const enemy = this.add.circle(
            Phaser.Math.Between(50, 750),
            Phaser.Math.Between(50, 550),
            Phaser.Math.Between(12, 18), // 随机初始大小
            0x0000ff // 蓝色敌人
        );
        this.physics.add.existing(enemy);
        enemy.body.setCollideWorldBounds(true);
        enemy.body.setBounce(0.3);
        enemy.mass = enemy.radius; // 质量等于半径
        enemy.target = null; // 当前目标(玩家或食物)
        enemies.add(enemy);
    }

    // 生成初始食物
    for (let i = 0; i < 20; i++) {
        createFood.call(this);
    }

    // 计分文本
    scoreText = this.add.text(16, 16, '分数: 0', { 
        fontSize: '32px', 
        fill: '#fff' 
    });

    // 添加调试图形
    this.debugGraphics = this.add.graphics();
    this.debugGraphics.setDepth(100);
    this.debugGraphics.visible = false;

    // 玩家与敌人碰撞(在update中手动检测)

    // 敌人之间碰撞
    this.physics.add.overlap(enemies, enemies, (enemy1, enemy2) => {
        // 敌人大20%以上才能吞噬另一个敌人
        if (enemy1.mass > enemy2.mass) {
            // enemy1吞噬enemy2
            enemy1.mass += enemy2.mass * 0.5;
            enemy1.setRadius(enemy1.mass);
            
            // 重置被吞噬的敌人
            enemy2.mass = 10;
            enemy2.setRadius(10);
            enemy2.setPosition(
                Phaser.Math.Between(50, 750),
                Phaser.Math.Between(50, 550)
            );
        } else if (enemy2.mass > enemy1.mass) {
            // enemy2吞噬enemy1
            enemy2.mass += enemy1.mass * 0.5;
            enemy2.setRadius(enemy2.mass);
            
            // 重置被吞噬的敌人
            enemy1.mass = 10;
            enemy1.setRadius(10);
            enemy1.setPosition(
                Phaser.Math.Between(50, 750),
                Phaser.Math.Between(50, 550)
            );
        }
    }, null, this);

    // 敌人与食物碰撞
    this.physics.add.overlap(enemies, food, (enemy, foodItem) => {
        // 敌人吃食物
        enemy.mass += 2; // 每次吃食物增加2点质量
        enemy.setRadius(enemy.mass);
        
        // 重置食物
        foodItem.setPosition(
            Phaser.Math.Between(50, 750),
            Phaser.Math.Between(50, 550)
        );
        foodItem.setFillStyle(Phaser.Display.Color.RandomRGB().color);
    }, null, this);
}

function update() {
    // 清除调试图形
    this.debugGraphics.clear();
    
    // 玩家控制
    const cursors = this.input.keyboard.createCursorKeys();
    const speed = 200 / (player.scale + 0.1); // 越大速度越慢
    
    // 手动检测玩家与食物碰撞
    food.getChildren().forEach(foodItem => {
        // 绘制碰撞范围(调试用)
        this.debugGraphics.lineStyle(1, 0xffff00);
        this.debugGraphics.strokeCircle(player.x, player.y, player.radius);
        this.debugGraphics.strokeCircle(foodItem.x, foodItem.y, foodItem.radius);
        
        // 计算两球中心距离
        const dx = player.x - foodItem.x;
        const dy = player.y - foodItem.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        // 计算重叠量(正数表示重叠)
        const overlap = (player.radius + foodItem.radius) - distance;
        
        // 有实际重叠才触发吞噬
        if (overlap > 0) {
            // 吞噬食物
            player.mass += 2; // 每次吃食物增加2点质量
            player.score += 10;
            player.setRadius(player.mass);
            
            // 更新分数显示
            scoreText.setText('分数: ' + player.score);
            
            // 重置食物
            foodItem.destroy();
            createFood.call(this);
        }
    });
    
    // 手动检测玩家与敌人碰撞
    enemies.getChildren().forEach(enemy => {
        // 绘制碰撞范围(调试用)
        this.debugGraphics.lineStyle(1, 0x00ff00);
        this.debugGraphics.strokeCircle(player.x, player.y, player.radius);
        this.debugGraphics.strokeCircle(enemy.x, enemy.y, enemy.radius);
        
        // 计算两球中心距离
        const dx = player.x - enemy.x;
        const dy = player.y - enemy.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        // 计算重叠量(正数表示重叠)
        const overlap = (player.radius + enemy.radius) - distance;
        
        // 玩家比敌人大且有实际重叠才触发吞噬
        if (player.mass > enemy.mass && overlap > 0) {
            // 吞噬敌人
            player.mass += enemy.mass * 0.5; // 获得50%质量
            player.score += enemy.mass;
            player.setRadius(player.mass);
            
            // 更新分数显示
            scoreText.setText('分数: ' + player.score);
            
            // 重置敌人
            enemy.mass = 10;
            enemy.setRadius(10);
            // 确保物理体与显示大小同步
            this.physics.world.disable(enemy);
            enemy.body = this.physics.add.existing(enemy).body;
            enemy.body.setCircle(10);
            enemy.setPosition(
                Phaser.Math.Between(50, 750),
                Phaser.Math.Between(50, 550)
            );
        } else if (enemy.mass > player.mass && overlap > 0) {
            // 被敌人吞噬 - 游戏结束
            this.physics.pause();
            player.setFillStyle(0xff0000);
            scoreText.setText('游戏结束! 分数: ' + player.score);
            this.debugGraphics.lineStyle(1, 0xff0000);
            this.debugGraphics.strokeCircle(player.x, player.y, player.radius);
            this.debugGraphics.strokeCircle(enemy.x, enemy.y, enemy.radius);
            
            // 显示重新开始按钮
            const restartButton = this.add.text(
                config.width / 2, 
                config.height / 2 + 50, 
                '重新开始', 
                { 
                    font: '24px Arial', 
                    fill: '#ffffff',
                    backgroundColor: '#333333',
                    padding: { x: 20, y: 10 }
                }
            );
            restartButton.setName('restartButton');
            restartButton.setOrigin(0.5);
            restartButton.setInteractive();
            restartButton.on('pointerdown', () => {
                this.scene.restart();
            });
        }
    });

    if (cursors.left.isDown) {
        player.body.setVelocityX(-speed);
    } else if (cursors.right.isDown) {
        player.body.setVelocityX(speed);
    } else {
        player.body.setVelocityX(0);
    }

    if (cursors.up.isDown) {
        player.body.setVelocityY(-speed);
    } else if (cursors.down.isDown) {
        player.body.setVelocityY(speed);
    } else {
        player.body.setVelocityY(0);
    }

    // 敌人AI - 智能行为
    enemies.getChildren().forEach(enemy => {
        const distanceToPlayer = Phaser.Math.Distance.Between(
            enemy.x, enemy.y,
            player.x, player.y
        );
        const enemySpeed = 15 / (enemy.scale + 0.1);

        // 只在200像素范围内对玩家做出反应
        if (distanceToPlayer < 200) {
            const angle = Phaser.Math.Angle.Between(
                enemy.x, enemy.y,
                player.x, player.y
            );
            
            // 根据体积决定追击或逃跑
            if (enemy.mass > player.mass * 1.2) {
                // 比玩家大则追击
                enemy.body.setVelocity(
                    Math.cos(angle) * enemySpeed,
                    Math.sin(angle) * enemySpeed
                );
                enemy.target = player;
            } else if (enemy.mass < player.mass * 0.8) {
                // 比玩家小则逃跑
                enemy.body.setVelocity(
                    Math.cos(angle) * -enemySpeed,
                    Math.sin(angle) * -enemySpeed
                );
                enemy.target = null;
            }
        } else {
            // 寻找最近的食物
            if (!enemy.target || !enemy.target.active) {
                let closestFood = null;
                let minDistance = Infinity;
                
                food.getChildren().forEach(foodItem => {
                    const dist = Phaser.Math.Distance.Between(
                        enemy.x, enemy.y,
                        foodItem.x, foodItem.y
                    );
                    if (dist < minDistance) {
                        minDistance = dist;
                        closestFood = foodItem;
                    }
                });
                
                enemy.target = closestFood;
            }
            
            // 向目标移动
            if (enemy.target) {
                const angle = Phaser.Math.Angle.Between(
                    enemy.x, enemy.y,
                    enemy.target.x, enemy.target.y
                );
                enemy.body.setVelocity(
                    Math.cos(angle) * enemySpeed,
                    Math.sin(angle) * enemySpeed
                );
            } else {
                // 没有目标则随机移动
                if (Phaser.Math.Between(0, 100) > 95) {
                    enemy.body.setVelocity(
                        Phaser.Math.Between(-50, 50),
                        Phaser.Math.Between(-50, 50)
                    );
                }
            }
        }
    });
}

function createFood() {
    const x = Phaser.Math.Between(0, config.width);
    const y = Phaser.Math.Between(0, config.height);
    const newFood = this.add.circle(x, y, 10, getRandomColor());
    //newFood.setStrokeStyle(2, 0xffffff); // 白色边框
    this.physics.world.enable(newFood);

    food.add(newFood);

        
    // 添加脉动效果
    this.tweens.add({
        targets: newFood,
        scale: { from: 1, to: 1.2 },
        duration: 1000,
        yoyo: true,
        repeat: -1
    });

}

function eatFood(player, foodItem) {
    foodItem.destroy();
    score += 10;
    scoreText.setText('分数: ' + score);
    player.setScale(player.scale + 0.02);
    createFood.call(this);
}